<?php
/**
 * 小班首页的数据。
 * Created by PhpStorm.
 * User: yaosj
 * Date: 16-5-21
 * Time: 下午7:45
 */
require __DIR__ . '/includes/utils.php';
require __DIR__ . '/includes/VipUtils.class.php';
class GetEntryData implements iController {

    public function output($queryArgs) {

        if (!validateUser($queryArgs))
            return genOutput(1000);

        $result = [
            //是否是小班成员
            'is_vip_member'   => $this->isVipMember($queryArgs['user_id']),
            //公告
            'announces'       => $this->getUnreadAnnounces($queryArgs),
            //作业
            'exercises'       => $this->getUndoneExercises($queryArgs['user_id'], $queryArgs['user_token']),
            //消息
            'notifications'   => $this->getUnreadNotifications($queryArgs['user_id'], $queryArgs['user_token']),
            //课堂
            'classroom'       => $this->getClassRoomList($queryArgs['user_id']),
            //统计
            'statistics'      => $this->getStatistics($queryArgs['user_id'], $queryArgs['user_token']),

        ];

        return genOutput(1, $result);
    }

    /**
     * 行测\天天模考 做题-统计信息
     *
     * @param $userId
     * @return array
     */
    private function getStatistics($userId) {

        // 全站最高  总量\正确率\估分\昨日总量
        $items = [
            'question_count'    => 0,
            'accuracy'          => 0,
            'score'             => 0,
//            'y_question_count'  => 0,
        ];

        //获取全站最高纪录
        $highestArr = getHighestByItems($items);

        //获取用户做题统计信息
        $userData = getUserData($userId);

        $exam_detail_id = '';
        $cacheKey       = 'func:getYesterdayQuestionCount:'.$exam_detail_id;
        $yesterdayCount = VipUtils::getUserDataGlobal($cacheKey);

        //昨日做题统计
        $yesterdayDate  = date('Ymd',strtotime("-1 day"));
        $cacheKeyUser   = 'func:getYesterdayQuestionCountByUser:' .$exam_detail_id.'_'.$userId;
        $yesterdayUserCount = VipUtils::getUserDataGlobal($cacheKeyUser);

        return $result = [
            'score'     => [
                'count'     => $userData->score > 100 ? 100 : $userData->score,
                'exceed'    => getUserDataRank($userData->exam_detail_id, 'score', $userData->score),
                'highest'   => $highestArr['score'] > 100 ? 100 : $highestArr['score'],
            ],
            'question_count'    => [
                'count'     => $userData->question_count,
                'exceed'    => getUserDataRank($userData->exam_detail_id, 'question_count', $userData->question_count),
                'highest'   => $highestArr['question_count'],
            ],
            'accuracy'  => [
                'count'     => round($userData->accuracy,4) * 100,
                'exceed'    => getUserDataRank($userData->exam_detail_id, 'accuracy', $userData->accuracy),
                'highest'   => round($highestArr['accuracy'],4) * 100,
            ],
            'y_question_count'    => [
                'count'     => isset($yesterdayUserCount[$yesterdayDate]) ? $yesterdayUserCount[$yesterdayDate] : 0,
                'exceed'    => getUserDataRank($userData->exam_detail_id, 'y_question_count', $userData->question_count,$userId),
                'highest'   => isset($yesterdayCount[$yesterdayDate]) ? $yesterdayCount[$yesterdayDate] : 0
            ],
        ];
    }

    /**
     * 获取最近三条未完成的作业
     * @param int $userId 用户id
     * @param string $userToken token
     * @return array
     */
    private function getUndoneExercises($userId, $userToken) {

        $results = ['total' => 0 ,'end_time' => '', 'list' => []];

        //通过接口获取未完成的作业
        $args = [
            'user_id'     => $userId,
            'user_token'  => $userToken,
            'category_id' => -1,
            'type_id'     => -1,
            'status_id'   => 9 //0 未完成  4 被驳回      6过期
        ];
        $exercises = getFilteredExercise($args);

        if (!empty($exercises))  {
            //未完成作业总数
            $results['total'] = count($exercises);
            //只取最近三条未完成作业
            foreach ($exercises as $k => $exercise) {
                if ($k > 2 )
                    break;
                if ($k == 0)
                    $results['end_time'] = $exercise['end_time'];
                $results['list'][] = $exercise;
            }
        }
        return $results;
    }

    /**
     * 获取未读的消息
     *
     * @param int $userId 用户id
     * @param int $userToken 用户token
     * @return array
     */
    private function getUnreadNotifications($userId, $userToken) {

        $results = ['total' => 0, 'unread_total' => 0, 'list' => []];

        $results['unread_total'] = intval(getUnreadNotificationsCount($userId));
        //通过接口获取最近一页的消息
        $args = [
            'user_id'     => $userId,
            'user_token'  => $userToken,
            'page'        => 1
        ];
        $notifications = getNotiFications($args);

        //过滤未读消息
        if (!empty($notifications)) {
            foreach ($notifications as $k => $n) {
                if (!$n['is_read']) {
                    //最近一页未读总数
                    $results['total']++;
                    if (!isset($results['list'][2]))
                        $results['list'][] = $n;
                }
            }
        }
        return $results;
    }

    /**
     * 获取未读的公告
     *
     * @param array $queryArgs
     * @return array
     */
    private function getUnreadAnnounces($queryArgs) {

        $results = ['total' => 0, 'list' => []];

        //通过接口获取最近一页的消息
        if (!empty($queryArgs['announce_id'])) {
            $announceId = intval($queryArgs['announce_id']);
        } else {
            $announceId = 0;
        }
        $announces = getAnnounceList($queryArgs['user_id'], $announceId);
        //过滤未读消息
        if (!empty($announces)) {
            foreach ($announces as $a) {
                if (!$a['is_read']) {
                    $results['total']++;
                    $results['list'][] = $a;
                }
            }
        }
        return $results;
    }

    /**
     * 获取课堂列表
     * @param $userId
     * @return array
     */
    private function getClassRoomList($userId) {

        $result = ['total' => 0,'start_time' => '', 'list' => []];

        $courseArr = getCourseListByUserId($userId);

        if (!empty($courseArr)) {

            foreach ($courseArr as $k => $v) {
                $data = getClassRoomListByCourseId($v['course_id']);
                $result['list'] = array_merge($result['list'], $data);
            }

            $dateArr = [];
            foreach ($result['list'] as $val) {
                $dateArr[] = $val['start_time'];
            }

            $result['start_time'] = !empty($dateArr) ? min($dateArr) : '';
            $result['total'] = count($result['list']);
        }
        return $result;
    }

    /**
     * 检测是否是小班成员
     * @param $user_id
     * @return bool
     */
    private function isVipMember($userId) {

        $result = getCourseListByUserId($userId, 9); //获取当前user的vip课程列表
        return !empty($result) ? true : false;
    }
}